//
//  TTRecyclingListOneSubViewController.m
//  TaoTuo
//
//  Created by LG on 2020/8/28.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTRecyclingListOneSubViewController.h"
#import "TTRecyclingListOneViewCell.h"
#import "TTEstimateDetailViewController.h"
#import "TTRecyclingGujiaModel.h"
#import "LLDateUtilis.h"

static NSString *cellID = @"cell";

@interface TTRecyclingListOneSubViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, assign) NSInteger status;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, nullable, strong) YYTimer *timer;

@end

@implementation TTRecyclingListOneSubViewController

- (instancetype)initWithStatus:(NSInteger)status
{
    self = [super init];
    if (self) {
        self.status = status;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.page = 1;
    @weakify(self)
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        [self loadFirstPageDatas];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        self.page++;
        [self requestDatas];
    }];
    
    [self requestDatas];
    
    /// 删除商品通知刷新页面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadFirstPageDatas) name:@"deleteGoods_notify_key" object:nil];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTRecyclingListOneViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    [cell setModel:self.dataArray[indexPath.row] cellType:self.status];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTRecyclingGujiaModel *model = self.dataArray[indexPath.row];
    
    TTEstimateDetailViewController *detailVC = [[TTEstimateDetailViewController alloc] init];
    detailVC.Reclaim_InformationId = model.Reclaim_InformationId;
    [[LLRouteTool getCurrentNavigationController] pushViewController:detailVC animated:YES];
}

- (void)loadFirstPageDatas
{
    self.page = 1;
    [self requestDatas];
}

// 计时
- (void)timerAction
{
    if (self.dataArray.count == 0) {
        return;
    }
    for (TTRecyclingGujiaModel *model in self.dataArray) {
        
        model.totalSecond++;
        
        model.hour = model.totalSecond / 3600;
        model.minute = model.totalSecond % 3600 / 60;
        model.second = model.totalSecond % 3600 % 60;
        
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"recyclingOneCellTimerNotify_key" object:nil];
    
}

- (void)requestDatas
{
    NSDictionary *dic = @{
        @"param.progress" : @(self.status + 1),
        @"param.pageIndex" : @(self.page),
        @"param.pageSize" : @20
    };
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:recycling_gujia_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        
        if (self.page == 1) {
            [self.dataArray removeAllObjects];
        }
        if (self.timer == nil) {
            self.timer = [YYTimer timerWithTimeInterval:1 target:self selector:@selector(timerAction) repeats:YES];
        }
        NSArray *array = responseObject[@"List"];
        for (NSDictionary *dic in array) {
            TTRecyclingGujiaModel *model = [TTRecyclingGujiaModel modelWithJSON:dic];
            if (model.Progress == 2) {
                // 当前时间
                NSString *currentDateStr = [LLDateUtilis getCurrentTimeString];
                // 时间差
                NSDateComponents *diff = [LLDateUtilis compareFromDateString:model.TriggerArtificialPriceTime toDateString:currentDateStr deteUnit:Hour | Minute | Second];
                model.hour = diff.hour >= 0 ? diff.hour : 0;
                model.minute = diff.minute >= 0 ? diff.minute : 0;
                model.second = diff.second >= 0 ? diff.second : 0;
                // 总秒数
                model.totalSecond = model.hour * 3600 + model.minute * 60 + model.second;
                [[NSNotificationCenter defaultCenter] postNotificationName:@"recyclingOneCellTimerNotify_key" object:nil];
            }
            [self.dataArray addObject:model];
        }
        
        if (array.count < 20) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        [self.tableView.mj_header endRefreshing];
        
        [self.tableView reloadData];
        
        NSDictionary *dic = @{
            @"0" : responseObject[@"EvaluationCount"],
            @"1" : responseObject[@"SendCount"],
            @"2" : responseObject[@"CheckCount"],
        };
        [[NSNotificationCenter defaultCenter] postNotificationName:@"setTopGoodsCountNotify_key" object:dic];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    } showLoadingInView:self.view];
    
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = kSeparatorColor;
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.rowHeight = 122;
        _tableView.emptyImageName = @"回收无数据页面";
        _tableView.emptyTitel = @"您还没有相关订单";
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[TTRecyclingListOneViewCell class] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideBottom);
        }];
    }
    return _tableView;
}


- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}



- (UIView *)listView
{
    return self.view;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.timer invalidate];
    self.timer = nil;
}

@end
